<?php
/*
 * @分销商城
 * @功能说明：首页栏目
 * @更新说明：暂无更新
 * @文件名 IndexController.class.php
 * @编码 UTF-8
 * @创建时间 2016-3-7 下午12:32:58
 * @创建人 XING
 */

namespace wap\Controller;
class IndexController extends ApibaseController
{
    /*
	 * 分销商城_首页模块
	 * @date: 2016-3-7 下午12:33:15
	 * @editor: XING
	 */
    public function index(){

        $this->display('index/index');
    }

    /*
     * π付系统-项目列表
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function projectList(){
        //不同积分类型显示对应可购买的项目(默认为普通项目)
        $score_type = I('get.score_type')?:1;
        $data = M('ProjectEntity')->where(['score_type'=>$score_type,'project_status'=>1, 'delete_at'=>0])->select();
        $data = $data ? :'';
        dataFormat($data,1,'success');
    }
    /*
     * π付系统-项目购买(传参project_id score_type)
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function project_buy(){
        if(I('post.project_id') && I('post.score_type')){
            $project = M('ProjectEntity')->where(['project_id'=>I('post.project_id')])->find();
            $type = I('post.score_type') == 1?'ordinary_score' : (I('post.score_type') == 2?'platina_score':(I('post.score_type') == 3?'diamonds_score':(I('post.score_type') == 4?'experience_score':(I('post.score_type') == 5?'gold_score':(I('post.score_type') == 6?'mouth_score':'')))));
            $score = M('UserInfo')->where(['user_id'=>session('loginUid')])->getField($type);
            $score_type = ['','普通','白金','钻石','体验','黄金','口腔'];
            if($score < $project['project_price']){
                dataFormat('',0,$score_type[I('post.score_type')].'账户积分不足');
            }
            $order_id = mkorder();
            //生成购买订单 扣掉用户相应积分
            $OrderEntity = M('OrderEntity');
            $UserInfo    = M('UserInfo');
            $ScoreDetail = M('ScoreDetail');
            $CardEntity  = M('CardEntity');
            $OrderEntity -> startTrans();
            $UserInfo    -> startTrans();
            $ScoreDetail -> startTrans();
            $CardEntity  -> startTrans();

            $rs = $OrderEntity->lock(true)->add([
                    'order_id'     => $order_id,
                    'user_id'      => session('loginUid'),
                    'user_mobile'  => session('loginMobile'),
                    'user_name'    => session('loginName'),
                    'project_id'   => I('post.project_id'),
                    'score_type'   => I('post.score_type'),
                    'order_amount' => $project['project_price'],
                    'add_at'       => time(),
                    'update_at'    => time(),
            ]);
            $content = explode(';',$project['content']);
            if($content){foreach ($content as $val){
                $arr = explode(',',$val);
                for($i=0;$i<$arr[1];$i++) {
                    $goods = M('GoodsEntity')->where(['goods_id'=>$arr[0]])->find();
                    $CardEntity->lock(true)->add([
                        'order_id'   => $order_id,
                        'user_id'    => session('loginUid'),
                        'goods_id'   => $arr[0],
                        'goods_name' => $goods['goods_name'],
                        'project_id' => $project['project_id'],
                        'is_used'    => 0,
                        'add_at'     =>time(),
                        'update_at'  =>time(),
                    ]);
                }

            }}

            $stype = I('post.score_type') == 1?'ordinary_score' : (I('post.score_type') == 2?'platina_score':(I('post.score_type') == 3?'diamonds_score':(I('post.score_type') == 4?'experience_score':(I('post.score_type') == 5?'gold_score':(I('post.score_type') == 6?'mouth_score':'')))));
            if($rs){
                $ScoreDetail->lock(true)->add([
                    'user_id'      => session('loginUid'),
                    'detail_type'  => 2,
                    'score_type'   => I('post.score_type'),
                    'detail_score' => $project['project_price'],
                    'remark'       => '购买套餐'.$project['project_name'],
                    'add_at'       => time(),
                    'update_at'    => time(),

                ]);
                $update = $UserInfo->lock(true)->where(['user_id'=>session('loginUid')])->setDec($stype,$project['project_price']);
                if($ScoreDetail && $update){
                    $OrderEntity->commit();
                    $UserInfo->commit();
                    $ScoreDetail->commit();
                    $CardEntity->commit();
                    dataFormat('',1,'购买成功');
                }else{
                    $OrderEntity->rollback();
                    $ScoreDetail->rollback();
                    $UserInfo->rollback();
                    $CardEntity->rollback();
                    dataFormat('',0,'购买失败');
                }
            }else{
                $OrderEntity->rollback();
                dataFormat('',0,'订单生成失败');
            }
        }else{
            dataFormat('',0,'参数缺失');
        }
    }

    /*
     * π付系统-订单列表(传参 订单号order_id)
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function orderList(){
    //不同积分类型显示对应订单列表(默认为普通项目订单)
        $score_type = I('get.score_type')?:1;
        $data = M('OrderEntity')->where(['score_type'=>$score_type,'user_id'=>session('loginUid')])->order('id desc')->select();
        if($data){
            foreach ($data as $k=>$val){
                $project = M('ProjectEntity')->where(['project_id'=>$val['project_id']])->find();
                $data[$k]['project_name'] = $project['project_name'];
                $data[$k]['cover_img']    = $project['cover_img'];
                $data[$k]['add_at']       = date('Y-m-d H:m:s',$val['add_at']);
                $data[$k]['delete_at']    = $val['delete_at']?date('Y-m-d H:m:s',$val['delete_at']):0;
            }
        }
        dataFormat($data,1,'success');
    }

    /*
     * π付系统-订单取消(传参 订单号order_id)
     * @date: 2018-02-09 上午10:33:15
     * @editor: yanyan
     */
    public function cancel_order(){
        $order_id = I('post.order_id');
        if(!$order_id){
            dataFormat('',0,'参数缺失');
        }
        $OrderEntity = M('OrderEntity');
        $UserInfo    = M('UserInfo');
        $ScoreDetail = M('ScoreDetail');
        $CardEntity  = M('CardEntity');
        $OrderEntity -> startTrans();
        $UserInfo    -> startTrans();
        $ScoreDetail -> startTrans();
        $CardEntity  -> startTrans();
        $order = $OrderEntity->where(['order_id'=>$order_id])->find();
        $order_update = $OrderEntity->lock(true)->where(['order_id'=>$order_id])->setField(['delete_at'=>time()]);
        $card_update = $CardEntity->lock(true)->where(['order_id'=>$order_id])->setField(['delete_at'=>time()]);
        $type = $order['score_type'] == 1?'ordinary_score' : ($order['score_type'] == 2?'platina_score':($order['score_type'] == 3?'diamonds_score':($order['score_type'] == 4?'experience_score':($order['score_type'] == 5?'gold_score':($order['score_type'] == 6?'mouth_score':'')))));

        if($order_update && $card_update){
            //取消成功 积分返回账户 生成对应的积分明细
            $detail_add = $ScoreDetail->lock(true)->add([
                'user_id'      => session('loginUid'),
                'detail_type'  => 3, //取消订单 积分返回+
                'score_type'   => $order['score_type'],
                'detail_score' => $order['order_amount'],
                'remark'       => '取消订单'.$order_id,
                'add_at'       => time(),
                'update_at'    => time(),

            ]);
            $score_return = $UserInfo->lock(true)->where(['user_id'=>session('loginUid')])->setInc($type,$order['order_amount']);

            if($detail_add && $score_return){
                $OrderEntity->commit();
                $UserInfo->commit();
                $ScoreDetail->commit();
                $CardEntity->commit();
                dataFormat('',1,'success');
            }else{
                $ScoreDetail->rollback();
                $UserInfo->rollback();
                dataFormat('',0,'error');
            }
        }else{
            $OrderEntity->rollback();
            $CardEntity->rollback();
            dataFormat('',0,'error');
        }
    }

    //订单套餐内容
    public function getContent(){
        if(I('post.project_id') && I('post.order_id')){
            $data = M('CardEntity')->where(['project_id'=>I('post.project_id'),'order_id'=>I('post.order_id')])->select();
            dataFormat($data,1,'success');
        }else{
            dataFormat('',0,'参数缺失');
        }
    }
    /*
     * π付系统-消费项目卡券(传参 订单号order_id)
     * 12-20 增加课室等五个参数
     * @date: 2017-12-20 下午13:41:26
     * @editor: yanyan
     */
    public function useCard(){
        if(I('post.order_id') && I('post.consumer') && I('post.consumer_mobile')){
            $rs = M('OrderEntity')->where(['order_id'=>I('post.order_id')])->setField([
                'consumer'        => I('post.consumer'),
                'consumer_mobile' => I('post.consumer_mobile'),
                'class_room'      => I('post.class_room'),
                'servicer'        => I('post.servicer'),
                'counselor'       => I('post.counselor'),
//                'operate_nurse'   => I('post.operate_nurse'),
                'operate_place'   => I('post.operate_place'),
                'is_used'         => 1,
                'use_at'          => time(),
                'update_at'       => time(),
            ]);
            if($rs){
                dataFormat('',1,'消费成功');
            }else{
                dataFormat('',0,'消费失败');
            }
        }else{
            dataFormat('',0,'参数缺失');
        }
    }

    /*
     * π付系统-消费套餐里的单个项目(18.1.29 操作医生改成选填)
     * @date: 2017-12-28 下午13:41:26
     * @editor: yanyan
     */
    public function useGood(){
        if(I('post.card_id') && I('operate_nurse') && I('operate_place')){
            $rs = M('CardEntity')->where(['card_id'=>['in',I('post.card_id')]])->setField([
                'operate_nurse' => I('operate_nurse'),
                'operate_doctor' => I('operate_doctor')?:'',
                'operate_place' => I('operate_place'),
                'is_used' => 1,
                'use_at'  => time(),
            ]);
            if($rs){
                dataFormat('',1,'success');
            }
        }else{
            dataFormat('',0,'参数缺失');
        }

    }

    /*
     * π付系统-订单详情(传参 订单号order_id)
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function order_detail(){
        if(I('get.order_id')){
            $order = M('OrderEntity')->where(['order_id'=>I('get.order_id')])->find();
            if($order['is_used']){
                $data = [
                    'consumer' => $order['consumer'],
                    'consumer_mobile' => $order['consumer_mobile'],
                    'use_at' => date('Y-m-d',$order['use_at']),
                ];
                dataFormat($data,1,'success');
            }else{
                dataFormat('',0,'未消费订单');
            }
        }else{
            dataFormat('',0,'error');
        }
    }

    /*
     * π付系统-充值页
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function recharge(){
        //返回需要充值的账户信息
        $bank = M('CashBank')->where(['id'=>1])->find();
        if($bank){
            dataFormat($bank,1,'success');
        }else{
            dataFormat('',0,'error');
        }
    }

    /*
     * π付系统-充值订单生成（参数 充值类型和金额）
     * @date: 2017-12-13 下午12:33:15
     * @editor: yanyan
     */
    public function recharge_order()
    {
        if (I('post.score_type') && I('post.recharge_money')) {
            $rs = M('UserRecharge')->add([
                'user_id' => session('loginUid'),
                'user_mobile' => session('loginMobile'),
                'user_name' => session('loginName'),
                'score_type' => I('post.score_type'),
                'recharge_money' => I('post.recharge_money'),
                'add_at' => time(),
                'update_at' => time(),
            ]);
            if($rs){
                dataFormat('',1,'success');
            }
        } else {
            dataFormat('',0,'error');
        }
    }
    /*
     * π付系统-充值记录
     * @date: 2017-12-14 下午16:33:15
     * @editor: yanyan
     */
    public function rechargeList(){
        $list = M('UserRecharge')->where(['user_id'=>session('loginUid')])->order('recharge_id desc')->select();
        dataFormat($list,1,'success');
    }
    /*
     * π付系统-取消充值(re_id)
     * @date: 2017-12-14 下午16:33:15
     * @editor: yanyan
     */
    public function cancle_recharge(){
        if(I('post.recharge_id')){
            $UserRecharge = M('UserRecharge');
            $is_have = $UserRecharge->where(['recharge_id'=>I('post.recharge_id'),'is_check'=>-1])->find();
            if($is_have){
                dataFormat('',0,'已取消请勿重复取消');
            }
            $update = $UserRecharge->where(['recharge_id'=>I('post.recharge_id')])->setField([
                'is_check'  => -1,
                'update_at' => time()
            ]);
            if ($update){
                dataFormat(['update_at'=>time()],1,'取消成功');
            }else{
                dataFormat('',0,'取消失败');
            }
        }else{
            dataFormat('',0,'参数缺失');
        }
    }
    /*
     * π付系统-个人资料
     * @date: 2017-12-14 下午16:33:15
     * @editor: yanyan
     */
    public function userInfo(){
        $data = [
            'user_name' => session('loginName'),
            'user_mobile' => session('loginMobile'),
        ];
        dataFormat($data,1,'success');
    }
    /*
     * π付系统-积分兑换
     * @date: 2017-12-26 下午16:33:15
     * @params score type(platina白金 diamonds钻石）
     * @editor: yanyan
     */
    public function exchange_score(){
        $score   = I('post.score');
        $type    = I('post.type'); //1白金 2钻石
        $user = M('UserInfo')->where(['user_id'=>session('loginUid')])->find();
        //判断普通账号积分是否大于要兑换的积分
        if($user['ordinary_score'] < $score){
            dataFormat('',0,'账户普通积分不足');
        }
        //1-23新增
        if(($score > $user['experience_score'])){
            dataFormat('',0,'账户体验积分不足');
        }
        $percent = $type == 1 ? '0.5' : ($type == 2 ? '0.416': ($type == 3 ? '0.735':''));
        $type_score = $type == 1 ? 'platina_score' : ($type == 2 ? 'diamonds_score' : ($type == 3 ? 'gold_score' : ''));
        $UserInfo = M('UserInfo');
        $ExchangeEntity = M('ExchangeEntity');
        $ScoreDetail = M('ScoreDetail');
        $UserInfo->startTrans();
        $ExchangeEntity->startTrans();
        $change_score = round(($score * $percent),2);
        //生成一条兑换记录 账号普通积分ordinary_score-$score 对应转入的积分+$score*$percent
        $insert = $ExchangeEntity->lock(true)->add([
            'exchange_type'    => $type,
            'user_id'          => session('loginUid'),
            'user_mobile'      => session('loginMobile'),
            'exchange_score'   => $score,
            'get_change_score' => $change_score,
            'add_at'           => time(),
            'update_at'        => time(),
        ]);
        //生成一条账户积分明细（普通积分减，兑换后的积分加）
        $decScore = $ScoreDetail->lock(true)->add([
            'user_id'      => session('loginUid'),
            'is_exchange'  => 1,
            'detail_score' => $score,
            'detail_type'  => 2, //消费使用
            'score_type'   => 1,  //普通积分
            'remark'       => '积分兑换',
            'add_at'       => time(),
            'update_at'    => time()
        ]);

        $decTyScore = $ScoreDetail->lock(true)->add([
              'user_id'      => session('loginUid'),
              'is_exchange'  => 1,
              'detail_score' => $score,
              'detail_type'  => 2, //消费使用
              'score_type'   => 4,  //普通积分
              'remark'       => '积分兑换',
              'add_at'       => time(),
              'update_at'    => time()
        ]);

        $IncScore = $ScoreDetail->lock(true)->add([
            'user_id'      => session('loginUid'),
            'is_exchange'  => 1,
            'detail_score' => $change_score,
            'detail_type'  => 1, //充值
            'score_type'   => $type == 3?($type+2):($type+1),
            'remark'       => '积分兑换获取',
            'add_at'       => time(),
            'update_at'    => time()
        ]);
        if($insert && $decScore && $decTyScore && $IncScore){
            $rs1 = $UserInfo->lock(true)->where(['user_id'=>session('loginUid')])->setDec('ordinary_score',$score);
            $rs2 = $UserInfo->lock(true)->where(['user_id'=>session('loginUid')])->setInc($type_score,$change_score);
            $rs3 = $UserInfo->lock(true)->where(['user_id'=>session('loginUid')])->setDec('experience_score',$score);
            if($rs1 && $rs2 && $rs3){
                $ExchangeEntity->commit();
                $UserInfo->commit();
                $ScoreDetail->commit();
                dataFormat('',1,'兑换成功');
            }else{
                $ExchangeEntity->rollback();
                $UserInfo->rollback();
                $ScoreDetail->rollback();
                dataFormat('',0,'兑换失败');
            }
        }else{
            $ExchangeEntity->rollback();
            $ScoreDetail->rollback();
            dataFormat('',0,'兑换记录生成失败');
        }
    }
    //指向页面
    public function user_center_recharge(){

        $this->display('index/user_center_recharge');
    }
    public function user_project_list(){
        $this->display('index/user_project_list');
    }
    public function user_order(){
        $this->display('index/user_order');
    }
    public function user_recharge_record(){
        $this->display('index/user_recharge_record');
    }
    public function change_password(){
        $this->display('index/change_password');
    }
    public function user_convertibility(){
        $this->display('index/user_convertibility');
    }
    public function user_post_order(){
        $this->display('index/user_post_order');
    }
    public function user_order_info(){
        $this->display('index/user_order_info');
    }
}
